package pcsync.server.gui;

import java.util.Observable;
import java.util.Observer;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.image.Image;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
import pcsync.server.ctrl.Controller;

public class ServerApp extends Application implements EventHandler<ActionEvent>, Observer
{
	private Scene serverAppScene;
	private TextArea console;
	private Button btnStartServer;
	private Button btnStopServer;
	
	private Controller controller;
	
	@Override
	public void init() throws Exception
	{
		super.init();
		controller = new Controller();
	}

	@Override
	public void start(Stage primaryStage)
	{
		// initialize graphical components
		
		btnStartServer = new Button("Start Server");
		btnStopServer = new Button("Stop Server");
		
		console = new TextArea();
		console.setText("Waiting for user action");
		console.setMaxHeight(100);
		console.setMaxWidth(600);
		
		// set event handlers on components
		
		btnStartServer.setOnAction(this);
		btnStopServer.setOnAction(this);
		
		// add the components to the interface
		
		FlowPane componentLayout = new FlowPane();
		componentLayout.setPadding(new Insets(10, 10, 10, 10));
		componentLayout.setHgap(10);
		componentLayout.setVgap(10);
		componentLayout.getChildren().add(btnStartServer);
		componentLayout.getChildren().add(btnStopServer);
		componentLayout.getChildren().add(console);

		// configure interface and display on screen
		
		serverAppScene = new Scene(componentLayout, 480, 190);
		
		primaryStage.getIcons().add(new Image("file:img/gtk-refresh.png"));
		primaryStage.setTitle("PCSync Server");
		primaryStage.setScene(serverAppScene);
		primaryStage.setWidth(500);
		primaryStage.setHeight(200);
		primaryStage.show();
	}
	
	public void printToConsole(String text)
	{
		console.appendText("\n" + text);
	}
	
	/* (non-Javadoc)
	 * @see javafx.event.EventHandler#handle(javafx.event.Event)
	 */
	@Override
	public void handle(ActionEvent event)
	{
		if (event.getSource().equals(btnStartServer))
		{
			printToConsole("Starting server...");
			controller.startServer();
		}
		else if( event.getSource().equals(btnStopServer))
		{
			printToConsole("Stopping server...");
			controller.stopServer();
		}
	}
	
	/* (non-Javadoc)
	 * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
	 */
	@Override
	public void update(Observable obs, Object arg)
	{
		
	}
	
	public static void main(String[] args)
	{
		launch(args);
	}
}